/*
 * @Author: 晴鸢. 3013433857@qq.com
 * @Date: 2025-11-05 08:09:49
 * @LastEditors: 晴鸢. 3013433857@qq.com
 * @LastEditTime: 2025-11-05 19:40:46
 * @FilePath: /Learn/Webself/protohol.hpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#pragma once
#include <iostream>
#include <string>
#include<json/json.h>
// 序列化和反序列化的功能
const std::string blank_space_sep = " ";
const std::string protocol_sep = "\n";
//len\n 报文
std::string Encode(std::string& content)
{
    std::string package=std::to_string(content.size());
    package+=protocol_sep;
    package+=content;
    package+=protocol_sep;
    return package;
}

bool Decode(std::string& package,std::string& content)
{
    //std::cout<<"decode:"<<package<<std::endl;
    size_t pos=package.find(protocol_sep);
    if(pos==std::string::npos)
        return false;
    std::string numlen=package.substr(0,pos);
    size_t num=std::stoi(numlen);
    size_t total_len=numlen.size()+num+2;
    if(package.size()<total_len)
        return false;
    content=package.substr(pos+1,num);
    package.erase(0,total_len);
    return true;
}

class Request
{
public:
    Request(){}
    ~Request(){}
    Request(int x,int y,char op)
    :_x(x),_y(y),_op(op)
    {}

    //x op y
    bool Serialize(std::string&content)
    {
        std::string str=std::to_string(_x);
        str+=blank_space_sep;
        str+=_op;
        str+=blank_space_sep;
        str+=std::to_string(_y);
        content=str;
        return true;
    }

    bool Deserialize(std::string&content)
    {
        int pos1=content.find(blank_space_sep);
        if(pos1==std::string::npos) return false;
        int pos2=content.rfind(blank_space_sep);
        if(pos2==std::string::npos) return false;
        if(pos1+2!=pos2) return false;
        _x=stoi(content.substr(0,pos1));
        _y=stoi(content.substr(pos2+1));
        _op=content[pos1+1];
        return true;
    }

    void Debugprint()
    {
        std::cout<<"请求构建完成："<<_x<<_op<<_y<<"=?"<<std::endl;
    }
public:
    int _x;
    int _y;
    char _op;
};

class Response
{
public:
    Response(){}
    Response(int result,int dcode)
    :  _result(result),_dcode(dcode)
    {}
    ~Response(){}
    //_result _dcode
    bool Serialize(std::string&content)
    {
        std::string str=std::to_string(_result);
        str+=blank_space_sep;
        str+=std::to_string(_dcode);
        content=str;
        return true;
    }

    bool Deserialize(std::string&content)
    {
        int pos=content.find(blank_space_sep);
        if(pos==std::string::npos) return false;
        _result=stoi(content.substr(0,pos));
        _dcode=stoi(content.substr(pos+1));
        return true;
    }   

    void Debugprint()
    {
        std::cout<<"result:"<<_result<<",dcode:"<<_dcode<<std::endl;
    }
public:
    int _result;
    int _dcode;
};